package jobs.job2;

import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

public class MyClient3 {
    Socket socket;

    String name;
    public MyClient3(int port) throws IOException {
        socket = new Socket("127.0.0.1", port);
        final Scanner scanner = new Scanner(socket.getInputStream());
        new Thread(){
            @Override
            public void run() {
                while (true) {
                    String line = scanner.nextLine();

                    String[] es = line.split("\0");
                    int code = Integer.parseInt(es[2]);
                    switch (code) {
                        case -1:
                            name = es[1];
                            System.out.println("-> 亲爱的`" + name + "` " + "，你好，欢迎加入聊天室");
                            break;
                        case -2:
                            System.out.println("-> 欢迎 `" + es[1] + "` " + "加入聊天室, 当前在线: " + es[0] + "人");
                            break;
                        default:
                            System.out.println("`" + es[1] + "`: " + es[0]);
                            break;
                    }
                }
            }
        }.start();

        new Thread(){
            @Override
            public void run() {
                try {
                    PrintStream out = new PrintStream(socket.getOutputStream());
                    Scanner in = new Scanner(System.in);
                    while (true) {
                        String line = in.nextLine();
                        out.println(line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();


    }

    public static void main(String[] args) throws IOException {
        new MyClient3(8888);
    }
}
